package com.example.demo.controller;
import com.example.demo.model.User;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.FileOutputStream;
/**
 *  导出1
 */
@Controller
public class ExcelController {
    @ResponseBody
    @GetMapping("toExcel")
    public String getExcel() {
        System.out.println("导出数据");
        //给实体赋值
        User user=new User();
        user.setId(1);
        user.setName("张三");
        user.setPassword("123456");
        //创建Excel文档中的头
        String[] headers = {"主键", "登录账号", "密码"};
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("用户表");
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(headers[i]);
        }
        //创建实体对象
        HSSFRow row1 = sheet.createRow(1);
        row1.createCell(0).setCellValue(user.getId());
        row1.createCell(1).setCellValue(user.getName());
        row1.createCell(2).setCellValue(user.getPassword());
        //将文档输出到客户端
        try {
          wb.write(new FileOutputStream("B:/BaiduNetdiskDownload/用户表.xls"));
        } catch (Exception e) {
            System.out.println("生成Excel失败原因为："+e.getMessage());
        }
        return "导出文件成功";
    }

}
